import random
import string
import sys

def generate_valid_palindrome(length):
    """生成有效回文串"""
    half_length = length // 2
    left_half = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(half_length))
    right_half = left_half[::-1]  # 反转左半部分
    return left_half + right_half

def generate_invalid_string(length):
    """生成无效回文串"""
    s = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
    # 随机修改一个字符确保不是回文
    if length > 1:
        pos = random.randint(0, length // 2 - 1)
        replacement = random.choice([c for c in string.ascii_letters + string.digits if c != s[pos]])
        s = s[:pos] + replacement + s[pos+1:]
    return s

def add_noise(s, noise_level=0.3):
    """添加非字母数字字符"""
    noisy_chars = []
    for c in s:
        if random.random() < noise_level:
            noisy_chars.append(random.choice(string.punctuation + ' '))
        noisy_chars.append(c)
    # 可能在末尾添加额外噪声
    if random.random() < noise_level:
        noisy_chars.append(random.choice(string.punctuation + ' '))
    return ''.join(noisy_chars)

def main():
    if len(sys.argv) != 3:
        print("Usage: python gen.py <length> <output_file>")
        sys.exit(1)
    
    length = int(sys.argv[1])
    output_file = sys.argv[2]
    
    # 随机决定生成有效或无效回文
    is_valid = random.choice([True, False])
    if is_valid:
        base = generate_valid_palindrome(length)
    else:
        base = generate_invalid_string(length)
    
    noisy_s = add_noise(base)
    
    with open(output_file, 'w') as f:
        f.write(noisy_s)
    
    print(f"Generated {'valid' if is_valid else 'invalid'} test case to {output_file}")

if __name__ == "__main__":
    main()    